package com.nononsenseapps.feeder.ui.rule


import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import cn.ekuma.odbo.mobile.ui.AbstractOdboSampleEditorDialog
import cn.ekuma.odbo.mobile.ui.EditorRecordHolder
import com.nononsenseapps.feeder.db.ARG
import com.nononsenseapps.feeder.db.entity.FeedRule
import com.nononsenseapps.feeder.db.room.ID_ALL_FEEDS
import com.nononsenseapps.feeder.db.room.ID_UNSET
import com.nononsenseapps.feeder.processor.RuleManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch

class FeedRuleEditorDialog: AbstractOdboSampleEditorDialog<FeedRule>() {

    private val feedRuleViewModel:FeedRuleEditorViewModel by viewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val item= FeedRule()
        var feedRuleId = ID_UNSET
        arguments?.let {arg->
            arg.getLong(ARG.FEED_ITEM_RULE_ID,ID_UNSET).let { feedRuleId = it }
            arg.getLong(ARG.FEED_ID).let { item.feedId=it }
            arg.getBoolean(ARG.AD_FLAG).let { item.adClick=it }
            arg.getString("regContext")?.let {
                item.title = it
                item.ruleValue = it
            }
        }
        if(feedRuleId != ID_UNSET){
            lifecycleScope.launch {
                 feedRuleViewModel.feedRuleDao.findFeedRuleById(feedRuleId).flowOn(Dispatchers.Main).collect {
                     editorRecordHolder.writeValueEdit(it)
                 }
            }
        }else
           editorRecordHolder.writeValueInsert(item)
    }

    override fun onCreateEditorRecordHolder(): EditorRecordHolder<FeedRule> =FeedRuleEditorHolder(lifecycleScope,requireContext(),feedRuleViewModel::loadSubscribeFeeds)

    override fun saveCurrentItem(item: FeedRule) {
        feedRuleViewModel.updateItem(item).let {
            Toast.makeText(this.requireContext(), "规则保存${item.title}/t id:${item.id}", Toast.LENGTH_SHORT).show()
            RuleManager.INSTANCE?.feedRuleChanged(item.feedId?: ID_ALL_FEEDS)
        }
    }

    override fun insertNewItem(item: FeedRule) {
       feedRuleViewModel.insertItem(item)
        Toast.makeText(this.requireContext(), "新增规则${item.title} /t id:${item.id}", Toast.LENGTH_SHORT).show()
        RuleManager.INSTANCE?.feedRuleChanged(item.feedId?: ID_ALL_FEEDS)
    }
}